package com.Sinewecology.EntropyWechat;

import java.io.IOException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import java.util.Map;

import com.entrogy.bean.PubCountEntity;
import org.apache.http.ParseException;

import com.entrogy.AccessToken.AccessTokenUpdate;
import com.Sinewecology.SendMessage.WechatMsgDataBean;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WX_TemplateMsgUtil {
    private static final Logger logger = LoggerFactory.getLogger(WX_TemplateMsgUtil.class);

	/**
	 * ��װģ����ϸ��Ϣ
	 * 
	 * @return
	 */
	public static JSONObject packJsonmsg(Map<String, TemplateData> param) {
		JSONObject json = new JSONObject();
		for (Map.Entry<String, TemplateData> entry : param.entrySet()) {
			JSONObject keyJson = new JSONObject();
			TemplateData dta = entry.getValue();
			keyJson.put("value", dta.getValue());
			keyJson.put("color", dta.getColor());
			json.put(entry.getKey(), keyJson);
		}
		return json;
	}

	/**
	 * ����ģ��ı�� ��������ȡģ��ID
	 * 
	 * @param templateSerialNumber ģ�����ģ��� "���"
	 * @return ģ��ID
	 * @throws IOException
	 * @throws ParseException
	 */
	public static String getWXTemplateMsgId(String templateSerialNumber,String accessToken) throws ParseException, IOException {
		String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="
				+ accessToken;
		JSONObject json = new JSONObject();
		json.put("template_id_short", templateSerialNumber);
		JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
		JSONObject resultJson = new JSONObject(result);
		String errmsg = (String) resultJson.get("errmsg");
//        log.info("��ȡģ���ŷ�����Ϣ��" + errmsg);
		if (!"ok".equals(errmsg)) {
			return "error";
		}
		String templateId = (String) resultJson.get("template_id");
		return templateId;
	}

	/**
	 * ����ģ��ID ɾ��ģ����Ϣ
	 * 
	 * @param templateId ģ��ID
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public static String deleteWXTemplateMsgById(String templateId,String accessToken) throws ParseException, IOException {
		String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token="
				+ accessToken;
		JSONObject json = new JSONObject();
		json.put("template_id", templateId);
		try {
			JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
			JSONObject resultJson = new JSONObject(result);
//            log.info("ɾ��"+templateId+"ģ����Ϣ,����CODE��"+ resultJson.get("errcode"));
			String errmsg = (String) resultJson.get("errmsg");
			if (!"ok".equals(errmsg)) {
				return "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	public static String sendWechatMsgToUser(JSONObject json, WechatMsgDataBean msgWX)
			throws ParseException, IOException {
//		String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
//				+ AccessTokenUpdate.wxTokenStr;
//
//		try {
//			JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
//			JSONObject resultJson = new JSONObject(result);
////            log.info("    ΢    Ϣ      Ϣ  " + resultJson.get("errcode"));
//			String errmsg = (String) resultJson.get("errmsg");
//
//			Log.log.info("平台发送结果 " + errmsg + " " + json.getString("touser"));
//			System.out.println("errmsg: " + errmsg);
//			if (!"ok".equals(errmsg)) { // ΪerrmsgΪok ͳɹ ں Ϣ û ˡ
//				return "error";
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return "error";
//		}
//		return "ok";       2019.3.1号  注释  xlr
		int count = 0;
		while (true) {
			String errmsg = sendWechatMsgMethod(json,msgWX);
			logger.info("平台发送结果 " + errmsg + " " + json.getString("touser"));
			if ("ok".equals(errmsg)) { // ���ΪerrmsgΪok��������ͳɹ������ں�������Ϣ���û��ˡ�
				return "ok";
			}
			count++;
			if (count >= 3) {// 超过 指定次数 给家长手机发送一条短信 TODO
				/*if (errmsg.contains("require subscribe hint")) {
					return "error";
				} else if (StrUtils.isNullOrEmpty(json.getString("touser"))) {
					return "error";
				} else {
					WillSendMessageList.insertToWechatMsgList(msgWX);
				}*/
//				StudentService studentService = new StudentService();
//				String openid = json.getString("touser");
//				StudentBean studentBean = studentService.getStudentByOpeid(openid);// 根据opeid 查询出其学生信息 家长电话号码 用
//																					// course_id封装
//				SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				// 发送离校短信
//				String[] params = {
//						"您的小孩" + studentBean.getStudent_name() + "已于" + format1.format(new Date()) + "离校，请您知晓。", "" };
//				SendUtils.sendByShortMessage(studentBean.getCourse_id(), params, "224729");
//				Log.log.info("平台发送失败后===短信==发送结果===》OK" + studentBean.getStudent_name());
				return "error";
			}
		}
		/*
		 * int count = 0; while (count <= 2) { String tmpurl =
		 * "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
		 * WX_TokenUtil.getWXToken();
		 * 
		 * try { JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "POST",
		 * json.toString()); JSONObject resultJson = new JSONObject(result); String
		 * errmsg = (String) resultJson.get("errmsg");
		 * 
		 * Log.log.info("平台发送结果 " + errmsg + " " + json.getString("touser"));
		 * System.out.println("errmsg: " + errmsg); if (!"ok".equals(errmsg)) { //
		 * ���ΪerrmsgΪok��������ͳɹ������ں�������Ϣ���û��ˡ� count++; continue; } else {
		 * break; } } catch (Exception e) { e.printStackTrace(); return "error"; } } if
		 * (count == 0) { return "ok"; } return "error";
		 */
	}

	private static String sendWechatMsgMethod(JSONObject json,WechatMsgDataBean wechatMsgDataBean) throws IOException {
		PubCountEntity pubCountEntity = wechatMsgDataBean.getPubCountEntity();
		if(null == pubCountEntity){
			return "error";
		}
		String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
				+ pubCountEntity.getAccessToken();
		String errmsg = null;
		try {
			JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
			JSONObject resultJson = new JSONObject(result);
//            log.info("����΢����Ϣ������Ϣ��" + resultJson.get("errcode"));
			errmsg = (String) resultJson.get("errmsg");

		} catch (Exception e) {
			e.printStackTrace();
			return errmsg;
		}
		return errmsg;
	}
}